<template>
  <div class="box">
    <el-divider content-position="left">添加排产</el-divider>
    <div class="formBox">
      <el-form
        :model="form"
        :rules="rules"
        ref="dialogForm"
        label-width="auto"
        label-position="right"
      >
        <el-form-item label="" style="width: 100%">
          <el-table
            ref="table"
            :data="productList"
            row-key="id"
            @selection-change="handleSelection"
            stripe
            border
          >
            <el-table-column type="selection" width="55"> </el-table-column>
            <el-table-column
              prop="contractName"
              label="合同名称"
              width="300"
              :show-overflow-tooltip="true"
            >
            </el-table-column>
            <el-table-column
              prop="name"
              label="产品名称"
              width="200"
              :show-overflow-tooltip="true"
            >
            </el-table-column>
            <el-table-column
              label="材质"
              prop="vproductMaterial"
              width="150"
              :show-overflow-tooltip="true"
            ></el-table-column>
            <el-table-column
              label="备注"
              prop="vproductRemark"
              width="100"
              :show-overflow-tooltip="true"
            ></el-table-column>
            <el-table-column prop="num" label="应排产数量" width="100">
              <template #default="scope">
                <p>{{ scope.row.num - scope.row.scheduledNum }}</p>
              </template>
            </el-table-column>
            <el-table-column prop="schedulingNum" label="生产设备" width="200">
              <template #default="scope">
                <el-select
                  v-model="scope.row.equipmentId"
                  placeholder="请选择设备"
                  clearable
                  :disabled="scope.row.sonSonList.length != 0"
                  style="width: 100%"
                  @visible-change="showSelect"
                >
                  <el-option
                    v-for="item in equipmentList"
                    :key="item.id"
                    :label="item.equipmentCode"
                    :value="item.id"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="排产数量" width="180">
              <template #default="scope">
                <el-input-number
                  :precision="0"
                  v-model.number="scope.row.schedulingNum"
                  placeholder="请输入数量"
                  @change="changeNum($event, scope.row)"
                ></el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="预计完成时间" width="300">
              <template #default="scope">
                <div class="rowTime">
                  <el-input-number
                    :precision="0"
                    v-model.number="scope.row.hour"
                    placeholder="请输入小时"
                    :disabled="scope.row.sonSonList.length != 0"
                  ></el-input-number>
                  <p>:</p>
                  <el-input-number
                    :precision="0"
                    v-model.number="scope.row.minute"
                    :max="60"
                    placeholder="请输入分钟"
                    :disabled="scope.row.sonSonList.length != 0"
                  ></el-input-number>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="unitName" label="单位" width="80">
            </el-table-column>
            <el-table-column label="图片" min-width="80">
              <template #default="scope">
                <sc-upload-multiple
                  v-model="scope.row.schedulingUrlList"
                  :limit="5"
                >
                </sc-upload-multiple>
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              fixed="right"
              align="center"
              width="100"
            >
              <template #default="scope">
                <el-button
                  text
                  type="primary"
                  size="small"
                  @click="handleDisassemble(scope.row, scope.$index)"
                  >拆解</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <div class="button">
        <el-button type="primary" @click="save" :loading="isSaveing"
          >保 存</el-button
        >
        <el-button @click="cencel">取 消</el-button>
      </div>
    </div>

    <el-dialog width="70%" title="拆解排产" v-model="visible" destroy-on-close>
      <sc-form-table
        ref="innerTable"
        :modelValue="disassembleProductList"
        :addTemplate="productsTemplate"
      >
        <el-table-column prop="productName" label="产品名称" width="250">
        </el-table-column>
        <el-table-column prop="name" label="拆解件名称" width="250">
          <template #default="scope">
            <el-input v-model="scope.row.name" placeholder="请输入拆解件名称" />
          </template>
        </el-table-column>
        <el-table-column prop="equipmentId" label="生产设备" width="200">
          <template #default="scope">
            <el-select
              v-model="scope.row.equipmentId"
              placeholder="请选择设备"
              clearable
              style="width: 100%"
              @visible-change="showSelect"
            >
              <el-option
                v-for="item in equipmentList"
                :key="item.id"
                :label="item.equipmentCode"
                :value="item.id"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="排产数量" width="180">
          <template #default="scope">
            <el-input-number
              :precision="0"
              v-model.number="scope.row.schedulingNum"
              placeholder="请输入数量"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="预计完成时间" width="300">
          <template #default="scope">
            <div class="rowTime">
              <el-input-number
                :precision="0"
                v-model.number="scope.row.hour"
                placeholder="请输入小时"
              ></el-input-number>
              <p>:</p>
              <el-input-number
                :precision="0"
                v-model.number="scope.row.minute"
                :max="60"
                placeholder="请输入分钟"
              ></el-input-number>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="图片" min-width="80">
          <template #default="scope">
            <sc-upload-multiple
              v-model="scope.row.schedulingUrlList"
              :limit="5"
            >
            </sc-upload-multiple>
          </template>
        </el-table-column>
      </sc-form-table>
      <template #footer>
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="setDisassembleData">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script>
export default {
  name: 'production',
  data () {
    return {
      visible: false,
      form: {
        // equipmentId: '',
        produceId: '',
        // estimateFinishTime: '',
        // startTime: this.$TOOL.dateFormat(new Date()),
        schedulingSonList: []
      },
      productList: [],
      equipmentList: [],
      selectionList: [],//被选择的产品
      source: null,//来源 0合同 1退货
      isSaveing: false,
      disassembleProductList: [],//拆解产品
      //拆解产品模版
      productsTemplate: {
        id: '',
        productName: '',
        name: '',
        equipmentId: '',
        schedulingNum: '',
        // finishHour: 0,
        hour: 0,
        minute: 0,
        schedulingUrlList: []//图片
      },
      rules: {
        equipmentId: [
          { required: true, message: '请选择设备', trigger: 'change' }
        ],
        estimateFinishTime: [
          { type: 'date', required: true, message: '请选择预计完成时间', trigger: 'change' }
        ],
      }
    }
  },
  mounted () {
    this.getProduceListByIds()
  },
  methods: {
    showSelect (val) {
      if (val) {
        this.getList()
      }

    },
    // 获取空闲设备
    async getList () {
      // type: 0//设备状态：0空闲1生产中
      let { data } = await this.$API.produce.equipment.getEquipmentList.get({ type: 0 })
      this.equipmentList = data
    },

    // 获取生产单详情
    async getProduceListByIds (ids) {
      let res = await this.$API.produce.getProduceListByIds.get({ ids: this.$route.query.ids })
      let list = res.data || []
      let p_list = []
      list.forEach(item => {
        item.produceProducts.forEach(i_item => {
          i_item.contractName = item.contractName
          i_item.schedulingNum = i_item.num - i_item.scheduledNum
          i_item.equipmentId = ''
          i_item.hour = 0
          i_item.minute = 0
          // i_item.finishHour = 0
          i_item.sonSonList = []
          i_item.schedulingUrlList = []
          p_list.push(i_item)
        })
      })
      this.productList = []
      p_list.map((item, index) => {
        if (item.num != item.scheduledNum) {
          this.productList.push(item)
        }
      })
      // this.productList = p_list
    },
    // 产品拆解排产
    handleDisassemble (row) {
      this.visible = true
      this.productsTemplate.productName = row.name
      this.productsTemplate.id = row.id
      this.productsTemplate.schedulingNum = row.schedulingNum
      if (row.sonSonList.length == 0) {
        this.disassembleProductList = []
        let template = {
          productName: row.name,
          id: row.id,
          name: '',
          equipmentId: '',
          schedulingNum: row.schedulingNum,
          hour: 0,
          minute: 0,
          schedulingUrlList: []
          // finishHour: 0,
        }
        this.disassembleProductList.push(template)

      } else {
        this.disassembleProductList = row.sonSonList
      }

    },

    // 拆解件数据
    setDisassembleData () {
      let flag = false
      let list = []
      this.disassembleProductList.forEach(item => {
        let time = item.hour + item.minute / 60
        if (item.name == '') {
          this.$message.error(`请填写拆解件名称`)
          flag = true
        }
        if (item.equipmentId == null || item.equipmentId == '') {
          this.$message.error(`请选择【${item.name}】的生产设备`)
          flag = true
        }
        if (item.schedulingNum == 0 || item.schedulingNum == null) {
          this.$message.error(`请填写【${item.name}】的排产数量`)
          flag = true
        }
        if (time == 0) {
          this.$message.error(`请填写【${item.name}】的预计完成时间`)
          flag = true
        }
      })
      if (flag) return
      this.productList.forEach(item => {
        this.disassembleProductList.forEach(d_item => {
          if (item.id == d_item.id) {
            let time = d_item.hour + d_item.minute / 60
            d_item.finishHour = time.toFixed(1)
            list.push({
              name: d_item.name,
              equipmentId: d_item.equipmentId,
              schedulingNum: d_item.schedulingNum,
              finishHour: time.toFixed(1),
              schedulingUrlList: d_item.schedulingUrlList
            })
            item.sonSonList = list
          }

        })

      })

      this.visible = false
      console.log(this.productList)
    },

    //选择产品
    handleSelection (list) {
      this.selectionList = list
      console.log(list)
    },
    // 排产数量改变
    changeNum (currentValue, item) {
      if (item.schedulingNum > (item.num - item.scheduledNum)) {
        item.schedulingNum = item.num - item.scheduledNum
        // this.$message.error(`【${data.name}】剩余数量不足，请重新填写排产数量`)
      }
    },
    async save () {
      this.$refs.dialogForm.validate(async (valid) => {
        if (valid) {
          if (this.selectionList.length == 0) {
            this.$message.error(`请选择产品排产`)
            return
          }
          let list = []
          let flag = false
          this.selectionList.map(item => {
            let time = item.hour + item.minute / 60
            list.push({
              produceId: item.produceId,
              productId: item.quotesProductId,
              schedulingNum: item.schedulingNum,
              equipmentId: item.equipmentId,
              finishHour: time.toFixed(2),
              isDismantle: item.sonSonList.length == 0 ? 0 : 1,//是否是拆解件 0否 1是
              schedulingUrlList: item.schedulingUrlList,
              sonSonList: item.sonSonList
            })
            if (item.equipmentId == null || item.equipmentId == '' && item.sonSonList.length == 0) {
              this.$message.error(`请选择【${item.name}】的生产设备`)
              flag = true
            }
            if (item.schedulingNum == 0 || item.schedulingNum == null) {
              this.$message.error(`请填写【${item.name}】的排产数量`)
              flag = true
            }
            // if (item.schedulingNum > (item.num - item.scheduledNum)) {
            //   this.$message.error(`【${item.name}】剩余数量不足，请重新填写排产数量`)
            //   flag = true
            // }
            if (time == 0 && item.sonSonList.length == 0) {
              this.$message.error(`请填写【${item.name}】的预计完成时间`)
              flag = true
            }
          })
          if (flag) return
          this.form.schedulingSonList = list
          this.form.produceId = this.$route.query.ids
          this.isSaveing = true
          let res = await this.$API.produce.addProduction.post(this.form)
          this.isSaveing = false
          this.$refs.dialogForm.resetFields()
          if (res.code == 200) {
            this.visible = false
            this.$router.push({
              path: "/produce/produceOrderManagement",
            })
          }
        } else {
          return false
        }
      })
    },

    // 取消
    cencel () {
      this.closeSelectedTag(this.$route)
      this.$router.push({
        path: "/produce/produceOrderManagement",
      })
    },
    //关闭tag
    closeSelectedTag (tag) {
      this.$store.commit("removeViewTags", tag)
      this.$store.commit("removeIframeList", tag)
      this.$store.commit("removeKeepLive", tag.name)
    },
  }
}
</script>
<style lang="scss" scoped>
.box {
  margin: 10px;
}

.formBox {
  padding: 30px;
  background: #fff;
  .el-form {
    width: 100%;
  }
}
.button {
  margin-top: 50px;
  padding-left: 60px;
}

:deep(.el-divider__text) {
  padding: 0 10px;
  font-size: 18px;
  // font-weight: 600;
  background-color: #f6f8f9;
}

.rowTime {
  display: flex;
  justify-content: space-around;
  align-items: center;
  p {
    margin: 0 3px;
  }
}
</style>